const db_promise = require("../config/db.config.js");
const logger = require('../util/logger');

async function getSingleIntent(req, res, next) {
  logger.winston.info('intents.getSingleIntents');
  
  try {
    	
    	 const [rows,fields] = await db_promise.query("select * from intents where intent_id = ?",[req.params.intent_id]);
    	 
    	 if (rows.length >= 1){
    	 	   rows_one = rows[0];
    	 }
    	 
    	 res.status(200).json(rows_one);    	 
    	 
    	
  }catch(err){

	    res.status(400).send({
	      message: err
	    });  

  }  
  

}

async function getBotIntents(req, res, next) {
  logger.winston.info('intents.getBotIntents');
  
  try {
    	
    	 const [rows,fields] = await db_promise.query("select * from intents where bot_id = ? order by intent_id desc",[req.params.bot_id]);
    	 res.status(200).json(rows);
    	
  }catch(err){

	    res.status(400).send({
	      message: err
	    });  

  }    
  

}

async function createBotIntent(req, res, next) {
  logger.winston.info('intents.createBotIntent');
  
  
    try {
    	
			  const [rows,fields] = await db_promise.query("insert into intents (bot_id, intent_name) values (?,?)", [req.body.bot_id, req.body.intent_name]);

        console.log(rows);			  
        if (rows.affectedRows >= 1){ 
			      res.status(200).json({ status: 'success', message: 'Updated' });
			  }else{
			  	  res.status(200).json({ status: 'no data', message: 'Updated' });
			  }    


  
    }catch(err){

		    res.status(400).send({
		      message: err
		    });  

	  }  
  

}

async function updateIntent(req, res, next) {
  logger.winston.info('intents.updateIntent');

    try {
    	
			  const [rows,fields] = await db_promise.query("update intents set intent_name = ? where intent_id = ?", [req.body.intent_name, req.params.intent_id]);

        console.log(rows);			  
        if (rows.affectedRows >= 1){ 
			      res.status(200).json({ status: 'success', message: 'Updated' });
			  }else{
			  	  res.status(200).json({ status: 'no data', message: 'Updated' });
			  }    


  
    }catch(err){

		    res.status(400).send({
		      message: err
		    });  

	  }


}

async function removeIntent(req, res, next) {
  //Remove all sub components of intent
  logger.winston.info('intents.removeIntent');

    try {
    	
			  const [rows,fields] = await db_promise.query("delete from intents where intent_id = ?", [req.params.intent_id]);

        console.log(rows);			  
        if (rows.affectedRows >= 1){ 
			      res.status(200).json({ status: 'success', message: 'Updated' });
			  }else{
			  	  res.status(200).json({ status: 'no data', message: 'Updated' });
			  }    


  
    }catch(err){

		    res.status(400).send({
		      message: err
		    });  

	  }


}

module.exports = {
  getBotIntents,
  createBotIntent,
  getSingleIntent,
  updateIntent,
  removeIntent
};
